package com.xpert.action.board;

	
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xpert.beans.Board;
import com.xpert.common.Constants;
import com.xpert.action.CommandAction;
import com.xpert.dao.BoardDao;

public class DownloadAction implements CommandAction {

	@Override
	public String requestProc(HttpServletRequest request,
					HttpServletResponse response) throws Throwable {

		request.setCharacterEncoding("euc-kr");
		int idx = Integer.parseInt(request.getParameter("idx"));

		Board article = BoardDao.getInstance().getArticle(idx);
		String filename = article.getFileName();

		//request.getRealPath("/upload")
		String uploadFileName = request.getSession().getServletContext().getRealPath(Constants.FILE_SAVE_DIR) + Constants.DIR_SEPARATOR_WIN + filename;

		File downFile = new File(uploadFileName);

		if(downFile.exists() && downFile.isFile()) {		// 다운로드
			try{
				long filesize = downFile.length();
				response.setContentType("application/x-msdownload");
				response.setContentLength((int)filesize);

				// user-agent : Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Win64; x64; Trident/7.0)
				String strClient = request.getHeader("user-agent");

				if(strClient.indexOf("MSIE 5.5") != -1) {
					response.setHeader("Content-Disposition", "filename=" + filename + ";" );
				}
				else {
					filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+","%20");
					// 인코딩 변경과 '+'문자 깨짐 방지
					response.setHeader("Content-Disposition", "attachment; filename=" + filename + ";" );
				}

				response.setHeader("Content-Length", String.valueOf(filesize));
				response.setHeader("Content-Transfer-Encoding", "binary;");
				response.setHeader("Pragma", "no-cache");
				response.setHeader("Cache-Control", "private");
				
				byte b[] = new byte[1024];
				BufferedInputStream fin = new BufferedInputStream(new FileInputStream(downFile));
				BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
				int read = 0;

				while((read=fin.read(b)) != -1) {
					outs.write(b, 0, read);
				}

				outs.flush();
				outs.close();
				fin.close();
		 }
		 catch(Exception e) {
				System.out.println("Download Exception : " + e.getMessage());
		 }
	}
	else {
			System.out.println("Download Error : downFile Error [" + downFile + "]");
	}

		 return null;
	}
}